package com.isyscore.os.metadata.kettle.base;

import org.pentaho.di.base.AbstractMeta;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.parameters.UnknownParamException;
import org.pentaho.di.trans.TransMeta;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public abstract class BaseGraphCodec implements GraphCodec {

    public void encodeInfo(AbstractMeta meta, FlowInfo transInfo) throws UnknownParamException {
        TransMeta transMeta = (TransMeta) meta;
        transMeta.setName(transInfo.getName());
    }

    public void decodeDatabases(List<FlowConnection> connections, AbstractMeta meta) throws Exception {
        Set<String> privateTransformationDatabases = new HashSet<String>(connections.size());
        for (FlowConnection connection : connections) {
            DatabaseMeta dbcon =  DatabaseCodec.decode(connection);
            dbcon.addExtraOption(dbcon.getPluginId(), "characterEncoding", "utf-8");
            dbcon.addExtraOption(dbcon.getPluginId(), "useSSL", "false");

            dbcon.addExtraOption(dbcon.getPluginId(), "useServerPrepStmts", "false");
            dbcon.addExtraOption(dbcon.getPluginId(), "rewriteBatchedStatements", "true");
            dbcon.addExtraOption(dbcon.getPluginId(), "useCompression", "true");
            dbcon.shareVariablesWith(meta);
            if (!dbcon.isShared()) {
                privateTransformationDatabases.add(dbcon.getName());
            }

            DatabaseMeta exist = meta.findDatabase(dbcon.getName());
            if (exist == null) {
                meta.addDatabase(dbcon);
            } else {
                if (!exist.isShared()) {
                    int idx = meta.indexOfDatabase(exist);
                    meta.removeDatabase(idx);
                    meta.addDatabase(idx, dbcon);
                }
            }
        }
        meta.setPrivateDatabases(privateTransformationDatabases);
    }
}
